﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Net;
using System.Collections;
using System.Diagnostics;
using Winforms = System.Windows.Forms;
using System.Threading;
using System.IO;
using System.Xml.Serialization;

namespace WebReader
{
    
    /// <summary>
    /// Логика взаимодействия для MainWindow.xaml
    /// </summary>
    public partial class F1Window : Window
    {
       

        private string adress = "http://www.f1news.ru/";
        public string loadedText = "";

        ArrayList arrLinksNew = new ArrayList();
        public Articles articles = new Articles();
        Articles articlesCurr = new Articles();
        string xmlName = "\\f1_Articles.xml";
 

        public string strKeyF1 = "newsList";
        Settings s;
        Winforms.Timer tmLink = new Winforms.Timer();
        Winforms.Timer tmAbort = new Winforms.Timer();

        Hyperlink hlCurr;
        int hintCurr = 0;
        string filePath = "";

        public int runCycle = 0;

        public F1Window(ref Settings _s, string _filePath)
        {
            s = _s;
            filePath = _filePath;
            InitializeComponent();
            FuncDownLoadText();
            SetTimerAbort();
            FuncFillLinksF1();          
            SetTimer();
           
        }

        public void DgDownLoadText(Object myObject, EventArgs myEventArgs)
        {
            ThreadPool.QueueUserWorkItem(DownLoadText);
        }

        public void DownLoadText(Object myObject)
        {
            FuncDownLoadText();
        }

        public void FuncDownLoadText()
        {
            try
            {
                WebClient wc = new WebClient();
                string str = Encoding.UTF8.GetString(Encoding.Convert(Encoding.GetEncoding(1251), Encoding.UTF8, wc.DownloadData(adress)));
                if (str != "") { loadedText = str; }
            }
            catch
            {
            }
        }


        public void SetTimer()
        {
            Winforms.Timer tm = new Winforms.Timer();
            tm.Interval = 620000;
            tm.Tick += new EventHandler(FillLinksF1);
            tm.Start();
            Winforms.Timer tmText = new Winforms.Timer();
            tmText.Interval = 520000;
            tmText.Tick += new EventHandler(DgDownLoadText);
            tmText.Start();
            
        }


        public void FillLinks(Object myObject)
        {
            FuncFillLinksF1();
        }

        public void FuncFillLinksF1()
        {
            DeSerial();
            try
            {
                if (loadedText != "")
                {
                    articlesCurr.articles.Clear();
                    string text = loadedText;
                    tbMain.Inlines.Clear();

                    text = text.Replace("<b>", "");
                    text = text.Replace("</b>", "");

                    int numCurr = 0;
                    int num = 0;
                    numCurr = text.IndexOf(strKeyF1);
                    int counter = 0;
                    while ((num = text.IndexOf("href", numCurr)) > 0 && runCycle == 1)
                    {
                        int numLink = 0;
                        int count = 0;
                        int startInd = num + 6;
                        string label = text.Substring(startInd, 10);
                        //if (label.Contains("interview"))
                        //{
                        //    num = text.IndexOf("href", startInd);
                        //    startInd = num + 6;
                        //}

                        int numLinkEnd = text.IndexOf("\"", startInd);
                        string name = "";
                        string link = "";
                        link = text.Substring(startInd, numLinkEnd - startInd);
                        int nameBegin = text.IndexOf(">", numLinkEnd);
                        int nameEnd = text.IndexOf("<", nameBegin);
                        name = text.Substring(nameBegin + 1, nameEnd - nameBegin - 1);
                        if (name != "" && !arrLinksNew.Contains(link))
                        {
                            AddLink("http://www.f1news.ru" + link, name);
                            numCurr = nameEnd;
                            counter++;
                        }
                        if (name == "" && link != "")
                        {
                            numCurr = nameEnd;
                        }

                        if (counter > 9)
                        {
                            articles = articlesCurr;
                            Serial();
                            ChangeViewLinks();
                            return;
                        }
                        num = 0;
                    }
                }
            }
            catch { }
         
        }

        public void TurnAbort(Object myObject, EventArgs myEventArgs)
        {
            runCycle = 0;
            tmAbort.Stop();
        }

        public void FillLinksF1(Object myObject, EventArgs myEventArgs)
        {
            arrLinksNew.Clear();
            SetTimerAbort();
            FuncFillLinksF1();
        }

        
        public void AddLink(string link, string name)
        {
            Link lk = new Link();
            lk.strLink =  link;           
            lk.strName = name;
            lk.isRead = false;
            foreach (Link item in articles.articles)
            {
                if (lk.strName == item.strName && item.isRead == true)
                {
                    lk.isRead = true;
                    break;
                }
            }
            articlesCurr.articles.Add(lk);
            //arrLinks.Add(lk);
            Run rn = new Run(lk.strName);
            Hyperlink hl = new Hyperlink(rn);
            hl.FontSize = 12.0;
            
            hl.Click += hl_Click;
            Uri ur = new Uri(link);
            hl.MouseLeave += hl_lostFocus;
            hl.MouseEnter += hl_getFocus;

            hl.NavigateUri = ur;
            hl.TextDecorations = new TextDecorationCollection();
            hl.ToolTip = name;
            if (lk.isRead == true)
            {
                hl.Foreground = Brushes.Black;
            }
            else
            {
                hl.Foreground = Brushes.Azure;
            }
            arrLinksNew.Add(hl);
           
           
          
        }

        public void ChangeViewLinks()
        {
            tbMain.Inlines.Clear();
            for (int i = 0; i < arrLinksNew.Count; i++)
            {
                tbMain.Inlines.Add((Hyperlink)arrLinksNew[i]);
                tbMain.Inlines.Add("\n");
            }


        }

        public void hl_Click(object sender, RoutedEventArgs e)
        {
            Process.Start((sender as Hyperlink).NavigateUri.ToString());
        }
        public void hl_lostFocus(object sender, MouseEventArgs e)
        {

            tmLink.Stop();


        }
        public void hl_getFocus(object sender, MouseEventArgs e)
        {

            hlCurr = (Hyperlink)sender;
            for (int i = arrLinksNew.Count - 1; i >= 0; i--)
            {

                if ((arrLinksNew[i] as Hyperlink).NavigateUri == hlCurr.NavigateUri)
                {
                    hintCurr = i;
                    break;
                }

            }



            SetTimerColor();
        }
        private void Window_MouseEnter(object sender, MouseEventArgs e)
        {

            brdMain.Background = new LinearGradientBrush(Color.FromArgb(255, 146, 145, 145), Color.FromArgb(255, 145, 145, 145), 90);
        }

        private void Window_MouseLeave(object sender, MouseEventArgs e)
        {
            brdMain.Background = new LinearGradientBrush(Color.FromArgb(130, 255, 255, 255), Color.FromArgb(130, 0, 0, 0), 90);
        }
        private void Window_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ChangedButton == MouseButton.Left)
                DragMove();
        }
        
        private void F1Reader_MouseMove(object sender, MouseEventArgs e)
        {
            s.FillCoordF1(Convert.ToInt32(F1Reader.Left), Convert.ToInt32(F1Reader.Top));
        }

        public void SetTimerAbort()
        {
            tmAbort.Interval = 120000;
            tmAbort.Tick += new EventHandler(TurnAbort);
            tmAbort.Start();
            runCycle = 1;
        }

        public void SetTimerColor()
        {
            tmLink.Interval = 300;
            tmLink.Tick += new EventHandler(ChangeColorLink);
            tmLink.Start();
        }
        public void FuncChangeColorLink()
        {
            Hyperlink l = (Hyperlink)arrLinksNew[hintCurr];
            l.Foreground = Brushes.Black;
            foreach (Link item in articles.articles)
            {
                if (item.strLink == l.NavigateUri.ToString())
                {
                    item.isRead = true;
                }
            }

            Serial();
        }
        public void ChangeColorLink(Object myObject, EventArgs myEventArgs)
        {
            FuncChangeColorLink();
        }



        /// <summary>
        /// записывание статей в файл
        /// </summary>
        public void Serial()
        {
            XmlHelper.Serial(filePath, xmlName, ref articles);

        }

        /// <summary>
        /// чтение статей из файла
        /// </summary>
        public void DeSerial()
        {

            XmlHelper.DeSerial(filePath, xmlName, ref articles);
        } 
    }

}
